package com.jlcloud.core.oauth2.config;

import lombok.AllArgsConstructor;
import com.jlcloud.core.jwt.props.JwtProperties;
import com.jlcloud.core.oauth2.granter.TokenGranter;
import com.jlcloud.core.oauth2.granter.TokenGranterEnhancer;
import com.jlcloud.core.oauth2.granter.TokenGranterFactory;
import com.jlcloud.core.oauth2.handler.*;
import com.jlcloud.core.oauth2.props.OAuth2Properties;
import com.jlcloud.core.oauth2.service.OAuth2ClientService;
import com.jlcloud.core.oauth2.service.OAuth2UserService;
import com.jlcloud.core.oauth2.service.impl.OAuth2ClientDetailService;
import com.jlcloud.core.oauth2.service.impl.OAuth2UserDetailService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

/**
 * OAuth2Configuration
 *
 * @author By: JlCloud <br>
 * @Package: com.jlcloud <br>
 * @CreateTime: 2024-12-03 21:45 <br>
 * @Copyright: 2021 www.jilianjituan.com Inc. All rights reserved. <br>
 * @Caution 注意：本内容仅限于冀联人力集团内部传阅，禁止外泄以及用于其他的商业目的 <br>
 */
@AllArgsConstructor
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(OAuth2Properties.class)
@ConditionalOnProperty(value = OAuth2Properties.PREFIX + ".enabled", havingValue = "true", matchIfMissing = true)
public class OAuth2AutoConfiguration {

	@Bean
	@ConditionalOnMissingBean
	public AuthorizationHandler authorizationHandler() {
		return new OAuth2AuthorizationHandler();
	}

	@Bean
	@ConditionalOnMissingBean
	public PasswordHandler passwordHandler(OAuth2Properties properties) {
		return new OAuth2PasswordHandler(properties);
	}

	@Bean
	@ConditionalOnMissingBean
	public TokenHandler tokenHandler(JwtProperties properties) {
		return new OAuth2TokenHandler(properties);
	}

	@Bean
	@ConditionalOnMissingBean
	public OAuth2ClientService oAuth2ClientService(JdbcTemplate jdbcTemplate) {
		return new OAuth2ClientDetailService(jdbcTemplate);
	}

	@Bean
	@ConditionalOnMissingBean
	public OAuth2UserService oAuth2UserService(JdbcTemplate jdbcTemplate) {
		return new OAuth2UserDetailService(jdbcTemplate);
	}

	@Bean
	public TokenGranterFactory tokenGranterFactory(List<TokenGranter> tokenGranters, List<TokenGranterEnhancer> tokenGranterEnhancers, OAuth2Properties properties) {
		return new TokenGranterFactory(tokenGranters, tokenGranterEnhancers, properties);
	}

}
